package com.xsw.framework.security.minilogin.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Sets;
import com.xsw.common.core.domain.entity.SysUser;
import com.xsw.common.core.domain.model.LoginUser;
import com.xsw.common.core.domain.model.MiniLoginBody;
import com.xsw.common.enums.UserStatus;
import com.xsw.common.exception.ServiceException;
import com.xsw.common.utils.SecurityUtils;
import com.xsw.common.utils.StringUtils;
import com.xsw.common.utils.mini.MiniUtils;
import com.xsw.framework.security.minilogin.service.MiniLoginUserDetailsService;
import com.xsw.framework.web.service.SysPasswordService;
import com.xsw.framework.web.service.SysPermissionService;
import com.xsw.system.mapper.SysUserMapper;
import com.xsw.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("miniLoginUserDetailsService")
public class MiniLoginUserDetailsServiceImpl implements MiniLoginUserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(MiniLoginUserDetailsServiceImpl.class);

    //账号初始密码
    private static final String INITPWD = "123456";
    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserService userService;

    @Resource
    private MiniUtils miniUtils;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String mobile, Object param) throws UsernameNotFoundException {


        // 此处即可自定义查询用户
        SysUser user = userService.selectUserByMobile(mobile);

        if (StringUtils.isNull(user)) {
            log.info("微信登录。当前手机号用户不存在，进行创建账号操作");
            try {
                //转化微信登录参数
                MiniLoginBody loginDTO = (MiniLoginBody) param;
                log.info("loginDTO:{}", loginDTO);
                JSONObject SessionKeyOpenId = miniUtils.getSessionKeyOrOpenId(loginDTO.getCode());
                log.info("SessionKeyOpenId:{}", SessionKeyOpenId);
                // 接收微信接口服务 获取返回的参数
                String sessionKey = SessionKeyOpenId.getString("session_key");
                String openid = SessionKeyOpenId.getString("openid");
                String unionid = SessionKeyOpenId.getString("unionid");
                String phone = miniUtils.getPhone(sessionKey, loginDTO);
                //防止第一次登录时，外部 微信登录调用方法拿不到手机号
                loginDTO.setPhone(phone);
                //更新手机号
                mobile = phone;

                user = userService.selectUserByMobile(mobile);
                if (StringUtils.isNull(user)) {
                    //自动新增微信账户
                    user = new SysUser();
                    user.setPhonenumber(mobile);
                    user.setUserName(mobile);
                    user.setNickName(mobile);
                    user.setSex("2");
                    user.setPassword(SecurityUtils.encryptPassword(INITPWD));
                    user.setUnionId(unionid);
                    user.setOpenId(openid);

                    sysUserMapper.insert(user);
                } else {
                    //更新账户信息
                    user.setUnionId(unionid);
                    user.setOpenId(openid);

                    sysUserMapper.updateById(user);
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("创建账号操作失败");
            }
            log.info("微信登录。手机号用户：{}，创建账号操作成功", mobile);
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", mobile);
            throw new ServiceException("对不起，您的账号：" + mobile + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", mobile);
            throw new ServiceException("对不起，您的账号：" + mobile + " 已停用");
        }

        //微信登录不需要密码校验
//        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        //permissionService.getMenuPermission(user)：PC端权限
        return new LoginUser(user.getUserId(), user.getDeptId(), user, Sets.newHashSet());
    }
}